package cn.wolfcode.luowowo.website.util;

import cn.wolfcode.luowowo.cache.util.RedisKeys;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {
    public static void addCookie(HttpServletResponse response, String key, String value,int time){
        //将token传入浏览器,就是将token存到cookie里面
        Cookie cookie = new Cookie(key,value);

        //设置cookie路径
        cookie.setPath("/");

        //设置限时时间
        cookie.setMaxAge(time);

        response.addCookie(cookie);
    }

    public static String getTonken(HttpServletRequest request,HttpServletResponse response){
        Cookie[] cookies = request.getCookies();
        String token = "";
        //以token为key获取redis中user对象
        if(cookies != null && cookies.length >0){

            for(Cookie cookie : cookies){

                if("token".equals(cookie.getName())){
                    //延长时间
                    cookie.setMaxAge(RedisKeys.USER_LOGIN.getTime().intValue());//intValue 转为int类型
                    cookie.setPath("/");
                    response.addCookie(cookie);
                    //获取真正的token对象
                    return cookie.getValue();
                }
            }
        }
        return null;
    }
}
